package logic

import (
	"context"
	"encoding/json"
	"time"
	"user_srv/cache"
	"user_srv/models/mysql"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookListLogic) BookList(in *user.BookListRequest) (*user.BookListResponse, error) {
	// todo: add your logic here and delete this line
	var book []mysql.Book
	key := "ShopList"
	mysql.Db.Where("novel_title like ?", "%"+in.Keyword+"%").Order("degree desc").Find(&book)
	var slice []*user.BookList
	get := cache.Rdb.Get(l.ctx, key)
	if get.Val() == "" {
		marshal, _ := json.Marshal(&slice)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	} else {
		json.Unmarshal([]byte(get.Val()), &slice)
	}

	for _, v := range book {
		list := user.BookList{
			UserId:     v.UserId,
			NovelTitle: v.NovelTitle,
			Writer:     v.Writer,
			BookCover:  v.BookCover,
			Degree:     v.Degree,
		}
		slice = append(slice, &list)
	}
	return &user.BookListResponse{
		Lisi: slice,
	}, nil
}
